package com.ligq.h265ttoupinreceive

import android.util.Log
import org.java_websocket.client.WebSocketClient
import org.java_websocket.handshake.ServerHandshake
import java.net.URI
import java.nio.ByteBuffer

const val TAG = "ligq--receive"

class SocketLive(private val callback: SocketCallBack, private val port: Int) {
    private lateinit var client: MyWebSocketClient

    inner class MyWebSocketClient(serverUri: URI) : WebSocketClient(serverUri) {
        override fun onOpen(handshakedata: ServerHandshake?) {
            Log.d(TAG, "onOpen: ")
        }

        override fun onMessage(message: String?) {
            Log.d(TAG, "onMessage: $message")
        }

        override fun onClose(code: Int, reason: String?, remote: Boolean) {
            Log.d(TAG, "onClose: ")
        }

        override fun onError(ex: Exception?) {
            Log.e(TAG, "onError: ", ex)
        }

        override fun onMessage(bytes: ByteBuffer?) {
            val data = ByteArray(bytes!!.remaining())
            bytes.get(data)
            callback.callback(data)
        }
    }

    fun start() {
        //ws://192.168.152.73:8099
        val uri = URI("ws://192.168.1.6:${port}")
        client = MyWebSocketClient(uri)
        try {
            client.connect()
        } catch (e: Exception) {
            Log.e(TAG, "start: ", e)
        }
    }

    interface SocketCallBack {
        fun callback(bytes: ByteArray)
    }
}